package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.PageResult;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.http.client.RedirectStrategy;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;



    @Override
    public String save(Video video) {
        //1、设置属性
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        //2、调用方法保存对象
        mongoTemplate.save(video);
        //3、返回对象id
        return video.getId().toHexString();
    }

    /**
     * 根据vid查询小视频列表
     */
    @Override
    public List<Video> findMovementsByVids(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").in(vids));
        return mongoTemplate.find(query,Video.class);
    }

    /**
     * 分页查询小视频数据
     */
    @Override
    public List<Video> queryVideoList(int page, Integer pagesize) {
        Query query = new Query().limit(pagesize).skip((page -1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }
    /**
     * 分页查询小视频评论数据
     */
    @Override
    public List<Comment> queryCommentList(int page, Integer pagesize) {
        Query query = new Query().limit(pagesize).skip((page -1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Comment.class);
    }

    @Override
    public PageResult findByUserId(Integer page, Integer pagesize, Long userId) {
        Query query = Query.query(Criteria.where("userId").in(userId));
        long count = mongoTemplate.count(query, Video.class);
        query.limit(pagesize).skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize,count,list);
    }

    //判断当前登录用户是否给视频点赞
    @Override
    public boolean judge(Long userId, String videoId) {
        Query query=new Query(Criteria
                .where("publishId").is(new ObjectId(videoId))
                .and("userId").is(userId)
                .and("commentType").is(1));
        return mongoTemplate.exists(query, Comment.class);
    }

    //添加数据,增加一条点赞,视频喜欢总数+1
    @Override
    public void saveLike(Long userId, String videoId) {
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        mongoTemplate.save(comment);

        Query query=Query.query(Criteria.where("id").is(new ObjectId(videoId)));
        Video video = mongoTemplate.findOne(query, Video.class);
        video.setLikeCount(+1);
        mongoTemplate.save(video);
    }

    //用户视频取消点赞
    @Override
    public void deleteLike(Long userId, String videoId) {
        Query query=new Query(Criteria
                .where("publishId").is(new ObjectId(videoId))
                .and("userId").is(userId)
                .and("commentType").is(1));
        mongoTemplate.remove(query, Comment.class);

        Query query1=Query.query(Criteria.where("id").is(new ObjectId(videoId)));
        Video video = mongoTemplate.findOne(query1, Video.class);
        video.setLikeCount(video.getLikeCount() -1);
        mongoTemplate.save(video);

    }

    //判断视频用户是否关注
    @Override
    public boolean judgeLove(Long userId, String videoId) {
        Query query = Query.query(Criteria
                .where("publishId").is(new ObjectId(videoId))
                .and("userId").is(userId)
                .and("commentType").is(3));//1点赞 2评论 3关注
        return mongoTemplate.exists(query, Comment.class);
    }

    //视频关注
    @Override
    public void saveLove(Long userId, String videoId) {
        //保存用户关注信息
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        mongoTemplate.save(comment);

        //视频表关注总数加一
        Query query = Query.query(Criteria.where("id").is(new ObjectId(videoId)));
        Video video = mongoTemplate.findOne(query, Video.class);
        video.setLoveCount(+1);
        mongoTemplate.save(video);

    }

    //视频取消关注
    @Override
    public void deleteLove(Long userId, String videoId) {
        //评论表 删除视频关注信息
        Query query =Query.query(Criteria.where("publishId").is(new ObjectId(videoId))
                .and("userId").is(userId)
                .and("commentType").is(3));
        mongoTemplate.remove(query,Comment.class);

        //视频表 关注总数减一
        Query query1 = Query.query(Criteria.where("id").is(new ObjectId(videoId)));
        Video video = mongoTemplate.findOne(query1, Video.class);
        video.setLoveCount(video.getLoveCount() -1);
        mongoTemplate.save(video);
    }

    //视频发布评论
    @Override
    public void saveComment(Comment comment1) {
        Video video = mongoTemplate.findById(comment1.getPublishId(), Video.class);
        //2、向comment对象设置被评论人属性
        if (video != null){
            comment1.setPublishUserId(video.getUserId());
        }
        mongoTemplate.save(comment1);
        Query query = Query.query(Criteria.where("id").is(comment1.getPublishId()));
        Update update = new Update();
        if(comment1.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",1);
        }else if (comment1.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",1);
        }else {
            update.inc("loveCount",1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        mongoTemplate.findAndModify(query,update, options, Video.class);
    }

    //判断视频评论是否点赞
    @Override
    public boolean judgeComments(ObjectId videoId, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(videoId)
                .and("commentType").is(2));
        return mongoTemplate.exists(query, Comment.class);

    }

    //保存评论点赞
    @Override
    public void saveLikeComment(ObjectId videoId, Long userId) {
        Query query = Query.query(Criteria.where("publishId").is(videoId)
                .and("commentType").is(2));
        Comment one = mongoTemplate.findOne(query, Comment.class);
        one.setLikeCount(one.getLikeCount() +1);
        mongoTemplate.save(one);
    }
    //视频评论取消点赞
    @Override
    public void deleteLikeComment(ObjectId videoId, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(videoId)
                .and("commentType").is(2)
                .and("likeCount").gt(0));
        Comment comment = mongoTemplate.findOne(query, Comment.class);
        comment.setLikeCount(comment.getLikeCount() -1);
        mongoTemplate.save(comment);
    }


}